package com.hb.znpt.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * The type File utils.
 */
public class FileUtils {

    private static final String TAG = "FileUtils";

    /**
     * Gets file doc dir.
     * 获取文档缓存目录
     *
     * @param context the context
     * @return the file doc dir
     */
    public static String getFileDocDir(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File docDir = context.getExternalFilesDir("doc");
            if (docDir != null && (docDir.exists() || docDir.mkdirs())) {
                return docDir.getAbsolutePath();
            }
        }
        return context.getCacheDir().getAbsolutePath();
    }

    /**
     * Gets tbs reader temp dir.
     * 获取tbs缓存目录
     *
     * @param context the context
     * @return the tbs reader temp dir
     */
    public static String getTbsReaderTempDir(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File tempDir = context.getExternalFilesDir("TbsReaderTemp");
            if (tempDir != null && (tempDir.exists() || tempDir.mkdirs())) {
                return tempDir.getAbsolutePath();
            }
        }
        return context.getCacheDir().getAbsolutePath();
    }

    /**
     * Gets persistence dir.
     * 获取持久化数据目录
     *
     * @param context the context
     * @return the persistence dir
     */
    public static String getPersistenceDir(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File tempDir = context.getExternalFilesDir("persistence");
            if (tempDir != null && (tempDir.exists() || tempDir.mkdirs())) {
                return tempDir.getAbsolutePath();
            }
        }
        return context.getCacheDir().getAbsolutePath();
    }

    /**
     * Gets photo dir.
     * 获取图片数据目录
     *
     * @param context the context
     * @return the persistence dir
     */
    public static String getPhotoDir(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File tempDir = context.getExternalFilesDir("photo");
            if (tempDir != null && (tempDir.exists() || tempDir.mkdirs())) {
                return tempDir.getAbsolutePath();
            }
        }
        return context.getCacheDir().getAbsolutePath();
    }

    /**
     * File is exists boolean.
     * 文件是否存在
     *
     * @param context  the context
     * @param fileName the file name
     * @return the boolean
     */
    public static boolean fileIsExists(Context context, String fileName) {
        List<String> paths = new ArrayList<>();
        File file = new File(getFileDocDir(context));
        File[] files = file.listFiles();
        if (files == null) {
            Log.e("error", "空目录");
            return false;
        } else {
            for (int i = 0; i < files.length; i++) {
                paths.add(files[i].getAbsolutePath());
            }
        }
        if (paths.size() == 0) {
            return false;
        } else {
            for (int i = 0; i < paths.size(); i++) {
                if (paths.get(i).contains(fileName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * File is exists boolean.
     * 文件是否存在
     *
     * @param dir      the dir
     * @param fileName the file name
     * @return the boolean
     */
    public static boolean fileIsExists(String dir, String fileName) {
        List<String> paths = new ArrayList<>();
        File file = new File(dir);
        File[] files = file.listFiles();
        if (files == null) {
            Log.e("error", "空目录");
            return false;
        } else {
            for (int i = 0; i < files.length; i++) {
                paths.add(files[i].getAbsolutePath());
            }
        }
        if (paths.size() == 0) {
            return false;
        } else {
            for (int i = 0; i < paths.size(); i++) {
                if (paths.get(i).contains(fileName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Gets file for name.
     * 获取文件名
     *
     * @param context  the context
     * @param fileName the file name
     * @return the file for name
     */
    public static String getFileForName(Context context, String fileName) {
        String path = "";
        List<String> paths = new ArrayList<>();
        File[] files = new File(getFileDocDir(context)).listFiles();

        for (int i = 0; i < files.length; i++) {
            paths.add(files[i].getAbsolutePath());
        }

        for (int i = 0; i < paths.size(); i++) {
            if (paths.get(i).contains(fileName)) {
                path = paths.get(i);
                break;
            }
        }

        return path;
    }

    /**
     * 文件是否存在
     *
     * @param strFile the str file
     * @return boolean boolean
     */
    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }


    /**
     * Gets mime type.
     * 获取文件媒体类型
     *
     * @param file the file
     * @return the mime type
     */
    public static String getMIMEType(File file) {
        String type = "*/*";
        String fName = file.getName();
        // 获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "")
            return type;
        // 在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }


    private static final String[][] MIME_MapTable = {
            // {后缀名，MIME类型}
            {".class", "application/octet-stream"},
            {".apk", "application/vnd.android.package-archive"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".exe", "application/octet-stream"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".msg", "application/vnd.ms-outlook"},
            {".jar", "application/java-archive"},
            {".js", "application/x-javascript"},
            {".rtf", "application/rtf"},
            {".tar", "application/x-tar"},
            {".wps", "application/vnd.ms-works"},
            {".zip", "application/x-zip-compressed"},
            {".tgz", "application/x-compressed"},
            {".bin", "application/octet-stream"},
            {".z", "application/x-compress"},
            {".pdf", "application/pdf"},
            {".bmp", "image/bmp"},
            {".gif", "image/gif"},
            {".png", "image/png"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".3gp", "video/3gpp"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp4", "video/mp4"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mpga", "audio/mpeg"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".ogg", "audio/ogg"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".c", "text/plain"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".java", "text/plain"},
            {".log", "text/plain"},
            {".prop", "text/plain"},
            {".rc", "text/plain"},
            {".sh", "text/plain"},
            {".txt", "text/plain"},
            {".xml", "text/plain"},
            {"", "*/*"}
    };
}
